import {
  Component, ElementRef, OnInit, Renderer, ViewChild, ViewEncapsulation, OnDestroy
} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {SeedInfiniteScroll} from 'app/shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {Content} from "app/shared/components/toolbar/toolbar-content";
import {Subject} from "rxjs/Subject";
import {TabComponent} from "app/shared/components/tab/tab.component";
import {MatchService} from "app/pages/match/match.service";
import {MatchDescriptionComponent} from './description/match-description.component';
import {MatchNoticeComponent} from './notice/match-notice.component';
import {MatchRulesComponent} from './rules/match-rules.component';

import {ToolsService} from "app/shared/service/tools/tools.service";
import {SeoService} from "app/core/seo/seo.service";
import {MatchScheduleComponent} from "./schedule/match-schedule.component";
import {MatchRankingComponent} from "./ranking/match-ranking.component";
import {MatchInfoHeadResp} from "../../../interface";


@Component({
  selector: 'competition-detail',
  templateUrl: './match-detail.component.html',
  styleUrls: ['./match-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class MatchDetailComponent implements OnInit, OnDestroy {
  public competitionBasicInfo: MatchInfoHeadResp;
  public dataStore = {
    matchId: 0, // 赛事ID
    matchType: 0, // 球类类型
    matchTypeArr: [3001, 3002, 3003, 3004, 3005, 300301, 300401, 300501], // 足球、篮球、羽毛球、网球、乒乓球
    scheduleType: 0, // 赛程类型
    scheduleTypeArr: [24005, 24007, 24011, 24017, 24024] // 淘汰赛、积分赛、杯赛、杯赛分离、积分赛单循环
  };
  public tabStore = {
    isMatch: false, // 赛程
    isRanking: false, // 排名
    currentTabTitle: '详情',
    loadedTabArr: [], // 已经加载过的tab
    unableTabArr: [], // 无更多数据的 tab
    noDataTabArr: ['详情', '章程', '公告'] // 没有数据的 tab
  };
  public pageDate = {
    isCup: false, // 是否杯赛
    isManager: false // 是否赛事管理员
  };

  @ViewChild(TabComponent) tabComponent;
  @ViewChild(MatchDescriptionComponent) infoTab;
  @ViewChild(MatchRulesComponent) rulesTab;
  @ViewChild(MatchScheduleComponent) matchTab;
  @ViewChild(MatchRankingComponent) rankingTab;
  @ViewChild(MatchNoticeComponent) noticeTab;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild(Content) content;
  @ViewChild('tab') tab: ElementRef;
  public ngUnsubscribe: Subject<any> = new Subject<any>();

  constructor(
    public route: ActivatedRoute,
    public service: MatchService,
    public renderer: Renderer,
    public router: Router,
    private _seoService: SeoService,
    public toolsServices: ToolsService
  ) {
  }

  /**
   * @description  获取赛事基本信息
   * @author ouyqx-691
   * @param matchId 赛事ID
   */
  getCompetitionBasicInfo() {
    this.service.getCompetitionBasicInfo(this.dataStore.matchId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.toolsServices.hideLoading();
      if (res.result === '0' && res.data) {
        this.competitionBasicInfo = res.data;
        this.dataStore.matchType = res.data.matchType;
        this.dataStore.scheduleType = res.data.scheduleType;
        this.handleTabCount();
        const competitionStore = this.service.competitionStore;
        competitionStore.competitionType = res.data.isTeam; // 存储团队类型
        competitionStore.scheduleType = res.data.scheduleType; // 存储赛赛程类型
        competitionStore.joinRequire = res.data.joinRequire; // 存储参赛者要求
        competitionStore.matchType = res.data.matchType; // 存储球类类型
        competitionStore.behalfSmallScore = res.data.behalfSmallScore; // 存储是否可以录入小比分
        this._seoService.setTKD(
          `${res.data.matchName}`,
          `${res.data.matchName}_赛事,赛事报名,比赛报名,赛事活动报名,赛事服务`,
          `求苗体育赛事报名服务管理平台，我们致力于以专业的赛事内容和产品，面向体育爱好者、俱乐部、体育机构和赛事组织者
      的全方位精准服务，打造体育产业链一流的互联网体育生态平台，让运动不仅能提升身心健康，更将成为社会运动潮流新标杆。`
        );

        competitionStore.cupCodeArr.filter((value) => {
          if (this.dataStore.scheduleType === value) {
            this.pageDate.isCup = true;
          }
        });
      }
    });
  }

  /**
   * @description 根据赛事类型控制 tab 个数
   * @author ouyqx-691
   * @param scheduleType ：赛事类型
   * @param matchType ：球类类型
   */
  handleTabCount() {
    const matchType = this.dataStore.matchType;
    const matchTypeArr = this.dataStore.matchTypeArr;
    const scheduleType = this.dataStore.scheduleType;
    const scheduleTypeArr = this.dataStore.scheduleTypeArr;

    // 不是淘汰赛并且不是积分赛和杯赛或者不是对应的球类不显示“赛程”和“排名”
    if (scheduleTypeArr.indexOf(scheduleType) === -1 || matchTypeArr.indexOf(matchType) === -1) {
      return;
    }

    if (scheduleType === 24005) { // 淘汰赛只显示“赛程”
      this.tabStore.isMatch = true;
    } else {
      // 积分赛[24007]、杯赛[24011]、杯赛分离[24017]“赛程”和“排名”都显示
      this.tabStore.isMatch = true;
      this.tabStore.isRanking = true;
    }
  }

  /**
   * 获取当前 tab 索引
   * @param index 当前 tab 索引
   */
  getTabIndex(tab: any) {
    const title = tab.title;
    this.tabStore.currentTabTitle = title;
    this.rsetInfiniteScrollState(title);
    // 当前 tab 已加载过则不再加载
    if (this.tabStore.loadedTabArr.indexOf(title) > -1) {
      return;
    }
    this.handleScrollLoad(title);
    this.tabStore.loadedTabArr.push(tab.title); // 加载一次后标记，下次点击不再加载
  }

  /**
   * @description 处理需要上滑加载更多的tab
   * @author ouyqx-691
   * @date 2017/08/23
   * @param index 当前tab 索引
   */
  handleScrollLoad(title: string) {
    switch (title) {
      case '详情':
        this.infoTab.getCompetitionInfo();
        break;
      case '章程':
        this.rulesTab.getCompetitionConstitution();
        break;
      case '赛程':
        if (this.pageDate.isCup) {
          // 为杯赛
          this.matchTab.getCupCompetitionSchedule();
        } else {
          // 淘汰赛、积分赛
          this.matchTab.getCompetitionSchedule();
        }
        break;
      case '排名':
        this.rankingTab.getCompetitionRanking();
        break;
      case '公告':
        this.noticeTab.getCompetitionNotice();
        break;
    }
  }

  /**
   * @description 重置滑动功能
   * @author ouyqx-691
   * @date 2017/10/10
   */
  rsetInfiniteScrollState(title: string) {
    if (this.tabStore.noDataTabArr.indexOf(title) > -1) { // 无数据
      this.infiniteScroll.enable(false); // 不可滑动
    } else {// 有数据
      if (this.tabStore.unableTabArr.indexOf(title) > -1) { // 已加载完
        this.infiniteScroll.enable(false); // 不可滑动
      } else {
        this.infiniteScroll.enable(true); // 可滑动
      }
    }
  }

  /**
   * @description 取消滑动事件
   * @param loadOver 有数据且已加载完？
   */
  disabledScroll(loadOver?: boolean) {
    const currentTabTitle = this.tabStore.currentTabTitle;
    if (loadOver) { // 有数据且数据已加载完
      this.tabStore.unableTabArr.push(currentTabTitle); // 若已无需上滑加载
    } else { // 无数据
      this.tabStore.noDataTabArr.push(currentTabTitle);
    }
    this.infiniteScroll.enable(false);
  }

  /**
   * @description 加载完成隐藏加载提示
   */
  scrollComplete() {
    this.infiniteScroll.complete();
  }

  /**
   * @description 重新打开滑动事件
   */
  enabledScroll() {
    this.infiniteScroll.enable(true);
  }

  /**
   * @description 固定 tab
   * @author ouyqx-691
   */
  fixedTab() {
    const container = this.content.content.nativeElement;
    let tabNavOffsetTop;
    this.renderer.listen(container, 'scroll', (e) => {
      tabNavOffsetTop = this.tab.nativeElement.getBoundingClientRect().top;
      const isFixed = this.tab.nativeElement.classList.contains('fixed');
      // const top = container.scrollTop;
      // console.log(top - tabNavOffsetTop, tabNavOffsetTop, top);
      // 50为没有更多数据 提示框高度

      if (tabNavOffsetTop < 0 && !isFixed) {
        this.tab.nativeElement.classList.add('fixed');
      }

      if (tabNavOffsetTop > 0 && isFixed) {
        this.tab.nativeElement.classList.remove('fixed');
      }
    });
  }

  /**
   * 前往发布者主页
   */
  goToPosterPage() {
    if (this.competitionBasicInfo.userId) {
      this.router.navigate([`/`, this.competitionBasicInfo.userId]);
    }
  }

  /**
   * 前往购买
   */
  goToGoodsDetailPagep() {
    const goodsCode = this.competitionBasicInfo.goodsCode ;
    if (goodsCode) {
      this.router.navigate(['/goods/detail', goodsCode]);
    }
  }

  /**
   * 判断是否是赛事管理员
   */
  getManagerValidate() {
    this.service.getManagerValidate(this.dataStore.matchId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.pageDate.isManager = res.data;
    });
  }

  ngOnInit() {
    this.toolsServices.showLoading();
    this.route.params.subscribe(params => {
      this.fixedTab();
      this.dataStore.matchId = params['matchId'];
      this.getCompetitionBasicInfo();
      this.getManagerValidate();
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
